//
//  HomeViewController.m
//  IMSDKDemo
//
//  Created by FungYan on 2022/5/5.
//

#import "CallViewController.h"
#import "HomeViewController.h"
#import "WeCloudIMSDK/WeCloudIMSDK.h"

@interface HomeViewController ()<WeCloudIMClientTRTCDelegate>
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UILabel *clientid;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[WeCloudIMClient sharedWeCloudIM] addTRTCListener:self];
    NSString *clientId =  [[NSUserDefaults standardUserDefaults] objectForKey:@"clientId"];
    self.clientid.text = clientId;
}
- (IBAction)copy:(UIButton *)sender {
    NSString *clientId =  [[NSUserDefaults standardUserDefaults] objectForKey:@"clientId"];
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = clientId;
}

- (IBAction)callStat:(UIButton *)sender {
    //发起音视频
    NSArray *numbers = [self.textField.text componentsSeparatedByString:@","];
    if (numbers.count<=0) {
        return;
    }
    
    __weak typeof(self) weakSelf = self;
    
   NSString * userId =  [[NSUserDefaults standardUserDefaults] objectForKey:@"clientId"];
    
    [WeCloudTRTCApi getSign:userId appKey:@"QizKVHcILRWp6Td2" timestamp:nil appSecret:@"287d04828099fb7de871e9dda845fa8b6b2302faf2ab3737" callback:^(BOOL success, NSString * _Nonnull sign, NSString * _Nonnull timestamp, WeCloudException * _Nonnull apiResult) {
        if (success) {
            [weakSelf getRoomIDAndToken:sign clientId:userId timestamp:timestamp];
        }
    }];
}

-(void)getRoomIDAndToken:(NSString *)sign clientId:(NSString *)clientId timestamp:(NSString *)timestamp{
    __weak typeof(self) weakSelf = self;
    [WeCloudTRTCApi getTokenWithClientId:clientId timestamp:timestamp appKey:@"QizKVHcILRWp6Td2" sign:sign callback:^(BOOL success, NSString * _Nonnull token, NSString * _Nonnull roomId, WeCloudException * _Nonnull apiResult) {
        if (success) {
            [weakSelf inviteUsers:roomId andToken:token];
        }
    }];
}


-(void)inviteUsers:(NSString *)roomId andToken:(NSString *)token{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSArray *numbers = [self.textField.text componentsSeparatedByString:@","];
        if (numbers.count<=0) {
            return;
        }
    __weak typeof(self) weakSelf = self;
        
        [[WeCloudIMClient sharedWeCloudIM]wcimInviteWithClientIds:numbers roomId:roomId callback:^(NSString * _Nonnull reqId, id  _Nullable responseData, NSError * _Nullable error, NSInteger responseCode) {
            if (!error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    CallViewController *callview = [CallViewController shared];
                    callview.roomID =  roomId;
                    callview.token =  token;
                    callview.isCall = YES;
                    callview.modalPresentationStyle = UIModalPresentationFullScreen;
                    [weakSelf presentViewController:callview animated:YES completion:nil];
                });
            }
        }];
    });
}
    

- (void)busyTRTC:(nonnull NSDictionary *)data {
    NSLog(@"用户忙");
}

- (void)joinTRTC:(nonnull NSDictionary *)data {
    NSLog(@"用户加入");
    NSString * userId =  [[NSUserDefaults standardUserDefaults] objectForKey:@"clientId"];
    CallViewController *callview = [CallViewController shared];
    //中途邀请
    if (callview.isCall || [data[@"clientId"] isEqualToString:userId]) {
        //邀请人是自己 是否已经进入房间
        BOOL isIn =  [[[NSUserDefaults standardUserDefaults]objectForKey:@"isInRoom"] boolValue];
        if (!isIn) {
            
            [callview insertRoom];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isInRoom"];
        }
    }
}

- (void)leaveTRTC:(nonnull NSDictionary *)data {
    NSLog(@"用户离开");
}

- (void)receiveTRTC:(nonnull NSDictionary *)data {
    NSLog(@"收到邀请");
    NSString * userId =  [[NSUserDefaults standardUserDefaults] objectForKey:@"clientId"];
    //是否是自己发起的
    CallViewController *callview = [CallViewController shared];
    if (!callview.isCall) {
        [self getSign:userId roomID:data[@"roomId"] timestamp:data[@"timestamp"]];
    }
}

- (void)refuseTRTC:(nonnull NSDictionary *)data {
    NSLog(@"用户拒绝");
}


#pragma mark - 网络请求 -- 被邀请者走的方法

-(void)getSign:(NSString *)userId
        roomID:(NSString *)roomId
     timestamp:(NSString *)timestamp
{
    
    __weak typeof(self) weakSelf = self;
    [WeCloudTRTCApi getSign:userId appKey:@"QizKVHcILRWp6Td2" timestamp:timestamp appSecret:@"287d04828099fb7de871e9dda845fa8b6b2302faf2ab3737" callback:^(BOOL success, NSString * _Nonnull sign, NSString * _Nonnull timestamp, WeCloudException * _Nonnull apiResult) {
        if (success) {
            [weakSelf getRoomIDAndToken:sign clientId:userId timestamp:timestamp roomId:roomId];
        }
    }];
}


-(void)getRoomIDAndToken:(NSString *)sign
                clientId:(NSString *)clientId
               timestamp:(NSString *)timestamp
                  roomId:(NSString *)roomId
{
    
    __weak typeof(self) weakSelf = self;
    [WeCloudTRTCApi inviterWithClientId:clientId timestamp:timestamp appKey:@"QizKVHcILRWp6Td2" sign:sign roomId:roomId callback:^(BOOL success, NSString * _Nonnull token, WeCloudException * _Nonnull apiResult) {
        if (success) {
            
            //判断是否有人进入房间 修改成获取VC的动态方法--> 在SDK声明方法继承
            dispatch_async(dispatch_get_main_queue(), ^{
                CallViewController *callview = [CallViewController shared];
                callview.roomID =  roomId;
                callview.token =  token;
                callview.isCall = NO;
                callview.modalPresentationStyle = UIModalPresentationFullScreen;
                [weakSelf presentViewController:callview animated:YES completion:nil];
            });
        }
    }];
}

@end
